package com.jianguozh.difs.support.service.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianguozh.difs.support.service.base.entity.Config;
import com.jianguozh.difs.support.service.base.mapper.ConfigMapper;
import com.jianguozh.difs.support.service.base.service.IConfigService;
import com.jianguozh.difs.support.service.component.file.core.client.DefaultFileClientSetting;
import com.jianguozh.difs.support.service.component.file.core.client.FileClientSetting;
import com.jianguozh.difs.support.service.component.setting.Setting;
import com.jianguozh.difs.support.service.constant.enums.ConfigTypeEnum;
import com.jianguozh.difs.support.service.constant.enums.FileStorageEnum;
import com.jianguozh.difs.support.service.utils.JsonUtils;
import com.jianguozh.difs.support.service.utils.ValidationUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Map;

/**
 * <p>
 * 配置 服务实现类
 * </p>
 *
 * @author hanrs
 * @since 2022-06-09
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Resource
    private Validator validator;

    @Override
    public Config getByType(ConfigTypeEnum configTypeEnum) {
        return this.getOne(new LambdaQueryWrapper<Config>().eq(Config::getConfigType, configTypeEnum));
    }

    @Override
    public Setting parseSetting(ConfigTypeEnum configTypeEnum, Map<String, Object> settingMap) {
        Class<? extends Setting> settingClass = configTypeEnum.getSettingClass();
        //文件存储器配置需要单独处理，从配置内再找配置
        if (configTypeEnum == ConfigTypeEnum.FILE_CLIENT_CONFIG) {
            FileClientSetting fileClientSetting = JsonUtils.parseObject2(JsonUtils.toJsonString(settingMap), DefaultFileClientSetting.class);
            ValidationUtils.validate(validator, fileClientSetting);
            String fileStorage = fileClientSetting.getFileStorage();
            FileStorageEnum fileStorageEnum = FileStorageEnum.valueOf(fileStorage);
            if (null == fileStorageEnum) {
                throw new IllegalArgumentException("fileStorage参数不合法.");
            }
            settingClass = fileStorageEnum.getConfigClass();
        }
        Setting setting = JsonUtils.parseObject2(JsonUtils.toJsonString(settingMap), settingClass);
        ValidationUtils.validate(validator, setting);
        return setting;
    }

}
